/*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef B2_WORLD_H
#define B2_WORLD_H

#include "../Common/b2Math.h"
#include "../Common/b2StackAllocator.h"
#include "../Common/b2BlockAllocator.h"
#include "b2ContactManager.h"
#include "b2WorldCallbacks.h"

struct b2AABB;
struct b2BodyDef;
struct b2JointDef;
class b2Body;
class b2Fixture;
class b2Joint;
class b2Contact;
class b2BroadPhase;
class b2Controller;
class b2ControllerDef;

struct b2TimeStep
{
	float32 dt;			// time step.
	float32 inv_dt;		// inverse time step.
	float32 dtRatio;	// dt * inv_dt0;
	int32 velocityIterations;
	int32 positionIterations;
	bool warmStarting;
};

// The world class manages all physics entities , dynamic simulation, and asynchroonous queries.The world also contains efficient memory management facilities.
class b2World
{
public:
	// Construct a world object.
	// @param worldAABB a bounding box that completely encompasses all your shapes.
	// @param gravity the world gravity vector.
	// @param doSleep improve performance by not simulating inactive bodies.
	b2World(const b2AABB& worldAABB, const b2Vec2& gravity, bool doSleep);

	// Destroy the world, All physics entities are destroyed and all heap memory is released.
	~b2World();

	// Register a destruction listener.
	void SetDestructionListener(b2DestructionListener* listener)	{ m_destructionListener = listener; }

	// Register a broad-phase boundary listener.
	void SetBoundaryListener(b2BoundaryListener* listener) { m_boundaryListener = listener; }

	// Register a contact filter to provide specific control over conllision.
	// Otherwise the default filter is used (b2_defaultFilter)
	void SetContactFilter(b2ContactFilter* filter) { m_contactFilter = filter; }

	// Register a contact event Listener.
	void SetContactListener(b2ContactListener* listener) { m_contactListener = listener; }

	// Register a routine for debug draw.the debug draw function are called inside the b2World::Step method.so make sure your renderer is ready to consume draw commands 
	// when you call Step();
	void SetDebugDraw(b2DebugDraw* debugDraw)	{ m_debugDraw = debugDraw; }

	// Create a rigid body given a definition.No reference to the definitionis is retained.
	// @warning This function is locked during callbacks.
	b2Body* CreateBody(const b2BodyDef* def);

	// Destruct a rigid body.
	// Warning this automatically deletes all associated shapes and joints.
	// Warning This function is locked during callbacks.
	void DestroyBody(b2Body* body);

	// Create a joint to constrains bodies together.This may cause the connected bodies to cease collision.
	// Warning This function is locked during callbacks.
	b2Joint* CreateJoint(const b2JointDef* jointDef);

	// Destroy a joint. This may cause the connected bodies begain colliding.
	// Warning This function is locked during callbacks.
	void DestroyJoint(b2Joint* joint);

	// Add a controller to the world.
	b2Controller* CreateController(const b2ControllerDef* def);

	// Remove a controller from the world.
	void DestroyController(b2Controller* controller);

	// The world provides a single static ground body with no collision shapes.
	// You can use this to simplify the creation of joints and static shapes.
	b2Body* GetGroundBody() { return m_groundBody; }

	// Take a time step.This perform collision detection, intergration, and constraint solution.
	// @param timeStep the amount of time to simulate this should not vary.
	// @param velocityIterations for the velocity constraint solver.
	// @param positionIterations for the position constraint solver.
	void Step(float32 timeStep, int32 velocityIterations, int32 positionIterations);

	// Query the world for all fixtures that potentially overlap the provide AABB.You provide a fixture pointer buffer of specified size.
	// The number of shape found is returned.
	// @param aabb the query box.
	// @param fixture a user allocated fixture pointer array of size maxCount 
	// @param maxCount the capacity of the shape array.
	// @return the number of fixture found in aabb.
	int32 Qerry(const b2AABB& aabb, b2Fixture** fixtures, int32 maxCount);

	// Query the world for all fixtures that intersect a given segment.You provide a fixture pointer buffer of specified size.
	// The number of fixture found is returned.and the buffer is filled in order of intersection.
	// @param segment define the begain and end point of the ray cast.
	// @param fixtures a user allocated fixture point array of size maxCount.
	// @param maxCount the capacity of the shape array.
	// @param solidShapes determines if shapes that the ray starts in are counted as hit.
	// @param userData pass through the world contact filter.with method Ray-collide. This can be used to filter valid shapes.
	// @return the number of the shape found.
	int32 Raycast(const b2Segment& segment, b2Fixture** fixtures, int32 maxCount, bool solidShapes, void* userData);

	// Performs a ray-cast with Raycast, finding the first intersecting fixture.
	// @param segment defines the begin and end point of the  ray cast.
	// @param lambda return the hit fraction. You can use this to compute contact point.
	// @param normal return the normal at contact point.
	// @param  solidShape determines if the shapes that the ray starts in are counted as hits.
	// @return the colliding shape.or null if not found.
	b2Fixture* RaycastOne(const b2Segment& segment, float32* lambda, b2Vec2* normal, bool solidShape, void* userData);

	// Check if the AABB is within the broad-phase limits.
	bool InRange(const b2AABB& aabb) const;

	// Get the world body list.With the return body.use b2Body::GetNext to get the next body in the world list.
	// A NULL body indicates the end of the list.
	// @return the head of the world body list.
	b2Body* GetBodyList() { return m_bodyList; }

	// Get the world joint list.With the return joint. use b2Joint::Getnext to get the next joint in the world list.
	// A NULL body indicates the end of the list.
	// @return the head of the joint list.
	b2Joint* GetJointList() { return m_jointList; }

	// Get the contact list. With the returned contact. use b2Contact::GetNext to get the next contact in the world list.
	// A NULL contact list indicates the end of the list.
	// @return the head of the contact list.
	b2Contact* GetContactList()	{ return m_contactList; }

	// Get the world controller list. with the returned controller. use b2Controller::GetNext to get the next controller in the world list.
	// A NULL controller indicates the end of the list.
	// return the head of the controller list.
	b2Controller* GetControllerList()	{ return m_controllerList; }

	// Re-filter a fixture.this re-runs contact filtering on a fixture.
	void Refilter(b2Fixture* fixture);

	// Enable/Disable warm starting. For testing.
	void SetWramStarting(bool flag) { m_warmStarting = flag; }

	// Enable / Disable continuous physics. For testing.
	void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }

	// Perform validation of internal data structure.
	void Validate();

	// Get the number of broad-phase proxies.
	int32 GetProxyCount() const;

	// Get the number of broad-phase pair.
	int32 GetPairCount() const;

	// Get the number of bodies.
	int32 GetBodyCount() const { return m_bodyCount; }

	// Get the number of joint.
	int32 GetJointCount() const { return m_jointCount; }

	// Get the number of contacts.
	int32 GetContactCount() const { return m_contactCount; }

	// Get the number of controller. 
	int32 GetControllerCount() const { return m_controllerCount; }

	// Change the global gravity vector.
	void SetGravity(const b2Vec2& gravity);

	// Get the global gravity vector.
	b2Vec2 GetGravity() const { return m_gravity; }

private:
	friend class b2Body;
	friend class b2ContactManager;
	friend class b2Controller;

	void Solve(const b2TimeStep& step);
	void SolveTOI(const b2TimeStep& step);

	void DrawJoint(b2Joint* joint);
	void DrawShape(b2Fixture* shape, const b2XForm& xf, const b2Color& color);
	void DrawDebugData();

	// Is it safe to pass private static functions pointers?
	static float32 RaycastSortKey(void* shape);

	b2BlockAllocator m_blockAllocator;
	b2StackAllocator m_stackAllocator;

	bool m_lock;

	b2BroadPhase* m_broadPhase;
	b2ContactManager m_contactManager;

	b2Body* m_bodyList;
	b2Joint* m_jointList;
	b2Controller* m_controllerList;

	b2Vec2 m_raycastNormal;
	void* m_raycastUserData;
	const b2Segment* m_raycastSegment;
	bool m_raycastSolidShape;

	// Do not access.
	b2Contact* m_contactList;

	int32 m_bodyCount;
	int32 m_contactCount;
	int32 m_jointCount;
	int32 m_controllerCount;

	b2Vec2 m_gravity;
	bool m_allowSleep;

	b2Body* m_groundBody;

	b2DestructionListener* m_destructionListener;
	b2BoundaryListener* m_boundaryListener;
	b2ContactFilter* m_contactFilter;
	b2ContactListener* m_contactListener;
	b2DebugDraw* m_debugDraw;

	// This is used to compute the time step ratio to support a variable time step.
	float32 m_inv_dt0;

	// This is for debugging the solver.
	bool m_warmStarting;

	// This is for debugging the solver.
	bool m_continuousPhysics;
};

#endif
